package cn.cxl.cxlutils.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

import androidx.annotation.Nullable;
import cn.cxl.cxlutils.utils.MyLog;



/*
 * 项目名:    studyDemo
 * 包名       com.lhd.study.view.test
 * 文件名:    ArcView
 * 创建者:    YHF
 * 创建时间:  2018/6/19 0019 on 17:21
 * 描述:     TODO
 */

@SuppressLint("AppCompatCustomView")
public class CustomView extends View {

    private Scroller scroller;
    private int lastX, lastY;

    public CustomView(Context context) {
        this(context, null);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        scroller = new Scroller(context);
    }

    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;

                break;
            case MotionEvent.ACTION_MOVE:
                int offsetX = x - lastX;
                int offsetY = y - lastY;
//                layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY);
                ((View) getParent()).scrollBy(-offsetX,-offsetY);
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller.computeScrollOffset()) {
//            ((View) getParent()).scrollTo(scroller.getCurrX(), scroller.getCurrY());
            MyLog.e("scroller",scroller.getCurrX()+" " +scroller.getCurrY());
            layout(-scroller.getCurrX(),getTop() -scroller.getCurrY(), getWidth() - scroller.getCurrX(), getBottom() - scroller.getCurrY());

            invalidate();
        }
    }

    public void smoothScrollTo(int destX, int destY) {
        int scrollX = getScrollX();
        int delta = destX - scrollX;
        scroller.startScroll(scrollX, 0, delta, 0, 2000);
        invalidate();

    }

}
